<template>
  <view class="container-wrap" :style="{ height: currentHeight }">
    <view class="title">
      <view @click="isFullScreenFn">订单进度</view>
      <view style="width: 150px">
        <uni-select v-model="buttonType" dataKey="name" dataValue="value" :clear="false" :localdata="buttonList"
          @change="buttonChange"></uni-select>
      </view>
    </view>
    <view v-if="!isShowPlace" class="echart-wrap">
      <echarts-uniapp v-show="buttonType === 1" ref="orderProcessRef" canvasId="orderProgressChart"
        @touchStart="touchStart" @touchEnd="touchEnd"></echarts-uniapp>
      <echarts-uniapp v-show="buttonType === 2" ref="orderAllProcessRef" canvasId="orderAllProgressChart"
        @touchStart="touchStart" @touchEnd="touchEnd"></echarts-uniapp>
    </view>
    <view v-if="isShowPlace" class="place-wrap">
      <view class="place-wrap flex-direction">
        <img :src="placePath" alt="" style="width: 200px; height: 110px" />
        <text>未关联采购订单，暂不支持查看该功能</text>
      </view>
    </view>
    <uni-loading v-show="showLoading"></uni-loading>
  </view>
</template>
<script>
  import config from '@/config';
  import { colorList, oITList } from './baseData.js';
  import * as echarts from '../common/echarts-uniapp/echarts.min.js';
  import echartsUniapp from '../common/echarts-uniapp/echarts-uniapp';
  import { orderProcessListsPur, orderAllProcessListsPur } from '@/api/dashboard';
  import uniLoading from '../common/uni-loading/uni-loading';
  export default {
    props: {
      currentHeight: {
        type: String,
        default: '100vh'
      }
    },
    components: {
      echartsUniapp,
      uniLoading
    },
    computed: {
      placePath() {
        return config.baseImgUrl + '/up-place.png';
      }
    },
    data() {
      return {
        showLoading: false,
        isShowPlace: false,
        pageIndex: 0,
        touchXStart: 0,
        buttonType: 1,
        buttonList: oITList,
        cacheList: [],
        orderProcessMap: {
          订单日计划车数: 'dayPlanVehicleNum',
          未出矿车数: 'notOreRemovalNum',
          在途车数: 'enRouteNum',
          停车场车数: 'parkingNum',
          站内车数: 'stationNum',
          已卸货车数: 'completeNum',
          合计总车数: 'totalNum'
        },
        orderAllMap: {
          卸货吨数: 'completeTon',
          到站吨数: 'pullInTon',
          出矿吨数: 'oreRemoval',
          总量: 'transportQuantity'
        },
        option: {
          color: colorList,
          tooltip: {
            show: true,
            trigger: 'axis',
            confine: true,
            responsive: true,
            axisPointer: {
              type: 'shadow'
            },
            textStyle: {
              testShadowColor: 'transparent',
              textShadowBlur: 10
            },
            padding: 5
          },
          grid: {
            left: 10,
            right: 10,
            top: 20,
            bottom: 0,
            containLabel: true
          },
          xAxis: {
            type: 'value',
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'category',
            splitLine: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {
              show: true,
              inside: true,
              verticalAlign: 'bottom',
              lineHeight: '36'
            },
            axisTick: {
              show: false
            },
            data: []
          },
          series: []
        }
      };
    },
    mounted() {
      this.orderProcessListsPurFn();
    },
    methods: {
      isFullScreenFn() {
        if (this.currentHeight === '100vh') {
          return;
        }
        this.$tab.navigateTo('/packageA/pages/purchaseTransport/orderProgress');
      },
      touchStart(e) {
        this.touchXStart = e.changedTouches[0].clientX || 0;
      },
      touchEnd(e) {
        const touchXEnd = e.changedTouches[0].clientX;
        if (this.touchXStart - touchXEnd > 0) {
          if (this.buttonType === 2) {
            if (this.cacheList.length - this.pageIndex - 3 > 0) {
              this.pageIndex = this.pageIndex + 3;
              this.setCharts1Option();
            }
          }
          if (this.buttonType === 1) {
            if (this.cacheList.length - this.pageIndex - 4 > 0) {
              this.pageIndex = this.pageIndex + 4;
              this.setChartsOption();
            }
          }
        }
        if (this.touchXStart - touchXEnd < 0) {
          if (this.pageIndex > 0) {
            if (this.buttonType === 2) {
              this.pageIndex = this.pageIndex - 3;
              this.setCharts1Option();
            } else {
              this.pageIndex = this.pageIndex - 4;
              this.setChartsOption();
            }
          }
        }
      },
      buttonChange() {
        this.pageIndex = 0;
        if (this.buttonType === 2) {
          this.isShowPlace = false
          this.orderAllProcessListsPurFn();
        } else {
          this.orderProcessListsPurFn();
        }
      },
      async orderProcessListsPurFn() {
        this.showLoading = true;
        const res = await orderProcessListsPur();
        if (res?.code === 0) {
          this.cacheList = (res?.data || []).map((e, v) => {
            e.id = `${e.coalSourceCoalType} ${v + 1}`;
            return e;
          });
          this.setChartsOption();
          this.showLoading = false;
          return
        }
        if (res?.code === 1000) {
          this.isShowPlace = true
          this.showLoading = false;
          return
        }
      },
      setChartsOption() {
        const result = JSON.parse(JSON.stringify(this.cacheList))
          .slice(this.pageIndex, 4 + this.pageIndex)
          .reverse();
        this.option.yAxis.axisLabel.lineHeight = 36;
        this.option.yAxis.data = result.map((e) => e.coalSourceCoalType);
        this.option.tooltip.formatter = this.getTooltip1();
        this.option.series = this.setSeries1List(result);
        this.$refs.orderProcessRef.initChart(this.option);
      },
      getTooltip1() {
        return (param) => {
          const obj = this.cacheList.find((e) => e.id === param[0].name);
          let paramStr = `${param[0].name.split(' ')[0]}\n\r`;
          param.forEach((item, index) => {
            const seriesName = item.seriesName;
            const value = obj[this.orderProcessMap[seriesName]];
            const marker = item.marker;
            if (index === param.length - 1) {
              paramStr += `${marker}${seriesName}: ${value ?? '-'}`;
            } else {
              paramStr += `${marker}${seriesName}: ${value ?? '-'}\n\r`;
            }
          });
          return paramStr;
        };
      },
      setSeries1List(result) {
        return [
          {
            name: '订单日计划车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'dayPlanVehicleNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#F1F8FF' },
                { offset: 1, color: '#409EFE' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          },
          {
            name: '未出矿车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'notOreRemovalNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#E3F4F0' },
                { offset: 1, color: '#27B57D' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          },
          {
            name: '在途车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'enRouteNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#FEF0E1' },
                { offset: 1, color: '#F78600' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          },
          {
            name: '停车场车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'parkingNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#F0EDFF' },
                { offset: 1, color: '#8B6FFE' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          },
          {
            name: '站内车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'stationNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#E0F7FB' },
                { offset: 1, color: '#00D1DE' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          },
          {
            name: '已卸货车数',
            type: 'bar',
            data: this.getSeriesValue(result, 'completeNum'),
            barWidth: 16,
            stack: 'total',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#FFE8E8' },
                { offset: 1, color: '#FF4D4F' }
              ])
            },
            showBackground: true,
            backgroundStyle: {
              color: '#EAF4FF'
            }
          }
        ];
      },
      async orderAllProcessListsPurFn() {
        this.showLoading = true;
        const res = await orderAllProcessListsPur();
        if (res?.code === 0) {
          this.cacheList = (res?.data || []).map((e, v) => {
            e.id = `${e.coalSourceCoalType} ${v + 1}`;
            return e;
          });
          this.setCharts1Option();
        }
        this.showLoading = false;
      },
      setCharts1Option() {
        const result = JSON.parse(JSON.stringify(this.cacheList))
          .slice(this.pageIndex, this.pageIndex + 3)
          .reverse();
        this.option.yAxis.axisLabel.lineHeight = 65;
        this.option.yAxis.data = result.map((e) => e.coalSourceCoalType);
        this.option.tooltip.formatter = this.getTooltip();
        this.option.series = this.setSeriesList(result);
        this.$refs.orderAllProcessRef.initChart(this.option);
      },
      setSeriesList(result) {
        return [
          {
            name: '卸货吨数',
            type: 'bar',
            data: this.getSeriesValue(result, 'completeTon'),
            barWidth: 8,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#FFECEC' },
                { offset: 1, color: '#FE4066' }
              ])
            }
          },
          {
            name: '到站吨数',
            type: 'bar',
            data: this.getSeriesValue(result, 'pullInTon'),
            barWidth: 8,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#FEF2E4' },
                { offset: 1, color: '#F78602' }
              ])
            }
          },
          {
            name: '出矿吨数',
            type: 'bar',
            data: this.getSeriesValue(result, 'oreRemoval'),
            barWidth: 8,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#E9F7F2' },
                { offset: 1, color: '#2EB780' }
              ])
            }
          },
          {
            name: '总量',
            type: 'bar',
            data: this.getSeriesValue(result, 'transportQuantity'),
            barWidth: 8,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#EAF4FF' },
                { offset: 1, color: '#419EFE' }
              ])
            }
          }
        ];
      },
      getTooltip() {
        return (param) => {
          const obj = this.cacheList.find((e) => e.id === param[0].name);
          let paramStr = `${param[0].name.split(' ')[0]}\n\r`;
          param.forEach((item, index) => {
            const seriesName = item.seriesName;
            const value = obj[this.orderAllMap[seriesName]];
            const marker = item.marker;
            if (index === param.length - 1) {
              paramStr += `${marker}${seriesName}: ${value ?? '-'}`;
            } else {
              paramStr += `${marker}${seriesName}: ${value ?? '-'}\n\r`;
            }
          });
          return paramStr;
        };
      },
      getSeriesValue(list, type) {
        let newList = [];
        if (this.buttonType === 2) {
          newList = this.getNomalBarList(list);
        } else {
          newList = this.getStackBarList(list);
        }
        const result = newList.map((e) => {
          if (type === 'dayPlanVehicleNum') {
            return {
              name: e.id,
              value: 0
            };
          }
          return {
            name: e.id,
            value: e[type]
          };
        });
        return result;
      },
      getStackBarList(list) {
        return list.map((e) => {
          let total = 0;
          const num = 100;
          if (e.notOreRemovalNum > 0) {
            total += e.notOreRemovalNum;
          }
          if (e.parkingNum > 0) {
            total += e.parkingNum;
          }
          if (e.enRouteNum > 0) {
            total += e.enRouteNum;
          }
          if (e.stationNum > 0) {
            total += e.stationNum;
          }
          if (e.completeNum > 0) {
            total += e.completeNum;
          }
          if (total) {
            const ratio = num / total;
            e.notOreRemovalNum =
              e.notOreRemovalNum > 0 ? e.notOreRemovalNum * ratio : 0;
            e.parkingNum = e.parkingNum > 0 ? e.parkingNum * ratio : 0;
            e.enRouteNum = e.enRouteNum > 0 ? e.enRouteNum * ratio : 0;
            e.stationNum = e.stationNum > 0 ? e.stationNum * ratio : 0;
            e.completeNum = e.completeNum > 0 ? e.completeNum * ratio : 0;
          }
          return e;
        });
      },
      getNomalBarList(list) {
        return list.map((e) => {
          const num = 100;
          const total = e.transportQuantity;
          if (total) {
            const ratio = num / total;
            e.completeTon =
              e.completeTon * ratio > num ? num : e.completeTon * ratio;
            e.pullInTon = e.pullInTon * ratio > num ? num : e.pullInTon * ratio;
            e.oreRemoval =
              e.oreRemoval * ratio > num ? num : e.oreRemoval * ratio;
            e.transportQuantity = 100;
          }
          return e;
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .container-wrap {
    position: relative;
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 15px 10px;
    background-color: #ffffff;
    border-radius: 8px;

    .title {
      display: flex;
      font-size: 14px;
      color: #000000;
      font-weight: 600;
      padding-bottom: 11px;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #e6e6e6;
    }

    .echart-wrap {
      flex: 1;
    }

    .place-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 30px 0;
    }

    .flex {
      display: flex;
    }

    .flex-direction {
      flex-direction: column;
    }

    .color {
      color: #fe4066;
      color: #f78602;
      color: #419efe;
      color: #2eb780;
      color: #07c8d9;
      color: #98429b;
    }
  }
</style>